<?php
declare(strict_types=1);

namespace Lshorz\LaravelConfig;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;

class CfgServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../config/cfg.php' => config_path('cfg.php'),
        ], 'config');

        $this->publishes([
            __DIR__.'/../cfg/.gitignore' => storage_path('/cfg/.gitignore'),
        ], 'config');

        $this->publishes([
            __DIR__.'/../database/migrations/create_cfg_table.php.stub' => $this->getMigrationFileName('create_cfg_table.php'),
        ], 'migrations');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register(): void
    {
        $this->app->singleton('Cfg', function ($app) {
            return new CfgManager($app);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides(): array
    {
        return ['Cfg', 'Cfg.driver'];
    }

    protected function getMigrationFileName($migrationFileName): string
    {
        $timestamp = date('Y_m_d_His');

        $filesystem = $this->app->make(Filesystem::class);

        return Collection::make($this->app->databasePath().DIRECTORY_SEPARATOR.'migrations'.DIRECTORY_SEPARATOR)
            ->flatMap(function ($path) use ($filesystem, $migrationFileName) {
                return $filesystem->glob($path.'*_'.$migrationFileName);
            })
            ->push($this->app->databasePath()."/migrations/{$timestamp}_{$migrationFileName}")
            ->first();
    }
}